/*
 * Copyright (c) Huawei Technologies Co., Ltd. 2022-2022. All rights reserved.
 */

package com.huawei.housekeeper.controller;

import com.huawei.housekeeper.utils.JwtTokenUtil;
import com.huawei.housekeeper.constant.Constant;

import com.alibaba.fastjson.JSONObject;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

import org.slf4j.MDC;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

/**
 * 日志埋点与记录
 *
 * @author lWX1128557
 * @since 2022-07-01
 */
@RestController
@Validated
@RequestMapping("/log")
@Api(tags = "事件追踪")
@Slf4j
public class LogController {

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @PostMapping(value = "/logger", consumes = "multipart/form-data;charset=UTF-8")
    @ApiOperation(value = "事件追踪")
    public void log(@Valid @RequestParam Map logDto, HttpServletRequest request) {
        String token = (String) logDto.get(Constant.TOKEN);
        String userId = null;
        if (token != null) {
            userId = jwtTokenUtil.getUserIdFromToken(token.substring(5));
        }
        String domain = request.getHeader("Referer");
        if (domain != null) {
            domain = domain.replace('\n', ' ').replace('\r', ' ');
            domain = domain.replaceAll(" ", "");
            log.info(request.toString());
            log.info("source domain " + domain);
            domain = domain.substring(7).split("\\.")[0];
            log.info("result domain " + domain);
        }
        MDC.put(Constant.TENANT_DOMAIN, domain);
        MDC.put(Constant.USER_ID, userId);

        JSONObject jsonObject = new JSONObject();
        jsonObject.put(Constant.INFORMATION, JSONObject.parseObject((String) logDto.get(Constant.INFORMATION)));
        jsonObject.put(Constant.ACTIONS, JSONObject.parse((String) logDto.get(Constant.ACTIONS)));
        jsonObject.put(Constant.PAGE, logDto.get(Constant.PAGE));
        jsonObject.put(Constant.TS, logDto.get(Constant.TS));
        jsonObject.put(Constant.MODEL, logDto.get(Constant.MODEL));
        jsonObject.put(Constant.SERVICE_ID, logDto.get(Constant.SERVICE_ID));
        log.info(jsonObject.toString());
    }
}
